﻿Imports System.Data
Imports CRM.BusinessLayer
Imports System.ComponentModel
Partial Public Class frmAdminSecurity

    Private Sub Txt_ExpiryDate_SelectedDateChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles Txt_ExpiryDate.SelectedDateChanged
        Me.Txt_ExpiryDate.Text = (New CommonFuncs).FormatDate(Txt_ExpiryDate.SelectedDate)
    End Sub

    Private Sub Txt_GroupExp_SelectedDateChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles Txt_GroupExp.SelectedDateChanged
        Me.Txt_GroupExp.Text = (New CommonFuncs).FormatDate(Txt_GroupExp.SelectedDate)
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub frmAdminSecurity_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        GeneralTasks.ChangeTheme(Me)
        GeneralTasks.EnumerateandFill(Me.LogicalChildren)
        With Me.List_Consultants
            .ItemsSource = Admin.ConsultantList
            .Columns(0).IsVisible = False
            .Columns(2).IsVisible = False
            .Columns(3).IsVisible = False
            .Columns(4).IsVisible = False
            .Columns(1).Width = New GridLength(155)
        End With
        FillListGroups()
        FillAddUserToGroupsCombo()

        With Me.Combo_GroupAddUser
            .ItemsSource = CType(Admin.ConsultantList, IListSource).GetList
            .SelectedValuePath = "Con Id"
            .DisplayMemberPath = "Name"
            .SelectedIndex = -1
        End With
        With Me.Combo_AddUserPermission
            .SelectedValuePath = "SecAccess_ID"
            .DisplayMemberPath = "SecAccess_Name"
            .ItemsSource = CType(Security.SecurityAccessList, IListSource).GetList
            .SelectedIndex = -1
        End With

        With Me.Combo_AddGroupPermission
            .SelectedValuePath = "SecAccess_ID"
            .DisplayMemberPath = "SecAccess_Name"
            .ItemsSource = CType(Security.SecurityAccessList, IListSource).GetList
            .SelectedIndex = -1
        End With
        'With Me.drpSecurityAccess
        '    .ValueMember = "SecAccess_ID"
        '    .DisplayMember = "SecAccess_Name"
        '    .DataSource = Security.SecurityAccessList
        '    .SelectedIndex = -1
        'End With
    End Sub
    Private Sub FillAddUserToGroupsCombo()
        With Me.Combo_AddUserToGroup
            .SelectedValuePath = "SecGroup_ID"
            .DisplayMemberPath = "Group Name"
            .ItemsSource = CType(Security.SecurityGroupList, IListSource).GetList
            .SelectedIndex = -1
        End With
    End Sub


    Private Sub FillListGroups()
        With Me.List_Groups
            .ItemsSource = Security.SecurityGroupList
            .Columns(0).IsVisible = False
            .Columns(1).Width = New GridLength(115)
        End With
    End Sub

    Private Sub List_Consultants_SelectionChanged(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.SelectionChangeEventArgs) Handles List_Consultants.SelectionChanged
        Me.FillGroupMemberShip()
        Me.List_UserGroupPermissions.ItemsSource = Nothing
        'Me.List_UserGroupPermissions.Requery()
        Me.ConsultantPermissions()
    End Sub
    Private Sub ConsultantPermissions()
        Dim StrSQL As String
        Dim selectedRow As DataRow = Me.List_Consultants.SelectedItem
        StrSQL = "SELECT Sec_Links.SecLink_ID, Sec_Access.SecAccess_Name as Permission, SecLink_DtExp as Expiry"
        StrSQL = StrSQL & " FROM Sec_Links INNER JOIN"
        StrSQL = StrSQL & " Sec_Access ON Sec_Links.SecLink_SecAccessID = Sec_Access.SecAccess_ID"
        StrSQL = StrSQL & " WHERE (Sec_Links.SecLink_ConsultantID = " & selectedRow(0) & ")"
        Dim consultantPermissions As DataTable = CommonDataFunctions.GetSQLDatatable(StrSQL)
        If Not consultantPermissions Is Nothing Then
            DataBinding.BindListView(consultantPermissions, List_ConsultantPermissions)
        End If
        'Me.List_ConsultantPermissions.ItemsSource = consultantPermissions
    End Sub
    Private Sub FillGroupMemberShip()
        Dim StrSQL As String
        Dim selectedRow As DataRow = Me.List_Consultants.SelectedItem
        If selectedRow Is Nothing Then
            Exit Sub
        End If
        StrSQL = "SELECT Sec_UserMembers.SecUserMember_ID, Sec_UserGroups.SecGroup_ID, Sec_UserGroups.SecGroup_Name as 'Group'"
        StrSQL = StrSQL & " FROM Sec_UserGroups INNER JOIN Sec_UserMembers ON Sec_UserGroups.SecGroup_ID = Sec_UserMembers.SecUserMember_UserGroupID"
        StrSQL = StrSQL & " WHERE (Sec_UserMembers.SecUserMember_ConsultantID = " & selectedRow(0) & ")"
        Dim groupMembers As DataTable = CommonDataFunctions.GetSQLDatatable(StrSQL)
        Me.List_GroupMembership.ItemsSource = groupMembers
        Me.List_GroupMembership.Columns(0).IsVisible = False
        Me.List_GroupMembership.Columns(1).IsVisible = False
        Me.List_GroupMembership.Columns(2).Width = New GridLength(150)
        'Call GblFunc_Populate_List(StrSQL, "Security_UserGroupsList", Form_FMA_Security.List_GroupMembership)

    End Sub
    Private Sub Btn_AddUserToGroup_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_AddUserToGroup.Click
        Try
            Dim StrSQL As String
            Dim selectedConsultant As DataRow = Me.List_Consultants.SelectedItem
            If selectedConsultant Is Nothing Or Me.Combo_AddUserToGroup.SelectedIndex = -1 Then
                Call MsgBox("Select values first", , "Error")
                Exit Sub
            End If

            StrSQL = "select * from Sec_UserMembers where SecUserMember_ConsultantID=" & selectedConsultant(0) & " and SecUserMember_UserGroupID=" & Me.Combo_AddUserToGroup.SelectedValue

            If (CommonDataFunctions.GetSQLDatatable(StrSQL)).Rows.Count > 0 Then
                CommonFuncs.DisplayMessage("The consultant is already belong to the group.", CommonDialog.CustomDialogIcons.Information, String.Empty)
                Exit Sub
            End If

            StrSQL = "Insert Into Sec_UserMembers"
            StrSQL = StrSQL & " (SecUserMember_ConsultantID, SecUserMember_UserGroupID, SecUserMember_EnteredBy)"
            StrSQL = StrSQL & " VALUES (" & selectedConsultant(0) & ", " & Me.Combo_AddUserToGroup.SelectedValue & ", '" & GlobalCRM.CurrentConName & "')"

            If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then Exit Sub

            FillGroupMemberShip()
            'Dim selectedItem As ComboBoxItem = Me.Combo_AddUserToGroup.SelectedItem

            Call (New TasksEvents).GblFunc_Add_SysEvent("Security", selectedConsultant(1) & " added to security group " & Me.Combo_AddUserToGroup.Text)

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminSecurity -Btn_AddUserToGroup_Click")
        End Try
        
    End Sub

    Private Sub Btn_RemoveUserFromGroup_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_RemoveUserFromGroup.Click
        Try
            Dim StrSQL As String
            Dim selectedMembership As DataRow = Me.List_GroupMembership.SelectedItem
            If selectedMembership Is Nothing Then
                Call CommonFuncs.DisplayMessage("Select group to remove from", CommonDialog.CustomDialogIcons.Information, String.Empty)
                Exit Sub
            End If

            StrSQL = "Delete from Sec_UserMembers where SecUserMember_ID = " & selectedMembership(0)
            If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then Exit Sub

            Me.FillGroupMemberShip()

            Me.List_UserGroupPermissions.ItemsSource = Nothing
            'Me.List_UserGroupPermissions.Requery()
            Dim selectedConsultant As DataRow = Me.List_Consultants.SelectedItem
            Call (New TasksEvents).GblFunc_Add_SysEvent("Security", selectedConsultant(1) & " removed from security group " & selectedMembership(1))

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminSecurity - Btn_RemoveUserFromGroup_Click")
        End Try
        
    End Sub

    Private Sub List_GroupMembership_SelectionChanged(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.SelectionChangeEventArgs) Handles List_GroupMembership.SelectionChanged

        Try
            Dim StrSQL As String
            Dim selectedMemberShip As DataRow = Me.List_GroupMembership.SelectedItem
            StrSQL = "SELECT Sec_Access.SecAccess_Name as Permission, SecLink_DTExp as Expiry"
            StrSQL = StrSQL & " FROM Sec_Links INNER JOIN"
            StrSQL = StrSQL & " Sec_Access ON Sec_Links.SecLink_SecAccessID = Sec_Access.SecAccess_ID"
            StrSQL = StrSQL & " WHERE (Sec_Links.SecLink_SecUserGroupID = " & selectedMemberShip(1) & ")"

            Dim userPermissions As DataTable = CommonDataFunctions.GetSQLDatatable(StrSQL)
            DataBinding.BindListView(userPermissions, List_UserGroupPermissions)
            'Call GblFunc_Populate_List(StrSQL, "Security_UserGroupsPermissions", Form_FMA_Security.List_UserGroupPermissions)

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminSecurity - List_GroupMembership_SelectionChanged")
        End Try
    End Sub

    Private Sub Btn_Remove_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_Remove.Click
        Try
            Dim StrSQL As String
            Dim selectedConsultantPermission As DataRowView = Me.List_ConsultantPermissions.SelectedItem
            If selectedConsultantPermission Is Nothing Then
                Call CommonFuncs.DisplayMessage("Please select permission to remove", CommonDialog.CustomDialogIcons.Information, String.Empty)
                Exit Sub
            End If

            StrSQL = "Delete from Sec_Links where SecLink_ID = " & selectedConsultantPermission(0)
            If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then Exit Sub

            Me.ConsultantPermissions()
            Dim selectedConsultant As DataRow = List_Consultants.SelectedItem

            Call (New TasksEvents).GblFunc_Add_SysEvent("Security", "Personal security permission " & selectedConsultantPermission(1) & " removed from user " & selectedConsultant(1))

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminSecurity - Btn_Remove_Click")
        End Try
    End Sub

    Private Sub Btn_AddUserPermission_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_AddUserPermission.Click
        Try
             Dim StrSQL As String, StrDT As String, StrMess As String
            Dim selectedConsultant As DataRow = Me.List_Consultants.SelectedItem
            If selectedConsultant Is Nothing Then
                Call CommonFuncs.DisplayMessage("Select values consultant first", CommonDialog.CustomDialogIcons.Information, "Consultant Not Selected")
                Exit Sub
            ElseIf Me.Combo_AddUserPermission.SelectedIndex = -1 Then
                Call CommonFuncs.DisplayMessage("Select values permission to add first", CommonDialog.CustomDialogIcons.Information, "Permission Not Selected")
                Exit Sub
            End If

            If Not Me.Txt_ExpiryDate.Text.Trim = String.Empty Then
                'If Not IsDate(Me.Txt_ExpiryDate) Then
                '    Call CommonFuncs.DisplayMessage("Please select a date", CommonDialog.CustomDialogIcons.Information, "Caution")
                '    Exit Sub
                'End If

                StrDT = "'" & Me.Txt_ExpiryDate.Text.Trim & "'"
                StrMess = ": Expires " & Me.Txt_ExpiryDate.Text
            Else
               
                StrDT = "Null"
                StrMess = ""
            End If

            StrSQL = "Insert into Sec_Links"
            StrSQL = StrSQL & " (SecLink_SecAccessID, SecLink_ConsultantID, SecLink_DTExp, SecLink_EnteredBy)"
            StrSQL = StrSQL & " Values(" & Me.Combo_AddUserPermission.SelectedValue & ", " & selectedConsultant(0) & ", " & StrDT & ", '" & GlobalCRM.CurrentConName & "')"

            If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then Exit Sub

            Me.ConsultantPermissions()
            Call (New TasksEvents).GblFunc_Add_SysEvent("Security", selectedConsultant(1) & " given security permission " & Me.Combo_AddUserPermission.Text & StrMess)
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminSecurity - Btn_AddUserPermission_Click")
        End Try
    End Sub

    Private Sub List_Groups_SelectionChanged(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.SelectionChangeEventArgs) Handles List_Groups.SelectionChanged
        Try
            FillListMembers()
            FillListGroupPermissions()
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminSecurity - List_Groups_SelectionChanged")
        End Try
    End Sub
    Private Sub FillListGroupPermissions()
        Dim StrSQL As String
        Dim selectedGroup As DataRow = Me.List_Groups.SelectedItem
        StrSQL = "SELECT Sec_Links.SecLink_ID, Sec_Access.SecAccess_Name ,SecLink_DtExp as Expiry"
        StrSQL = StrSQL & " FROM Sec_Links INNER JOIN Sec_Access ON Sec_Links.SecLink_SecAccessID = Sec_Access.SecAccess_ID"
        StrSQL = StrSQL & " WHERE (Sec_Links.SecLink_SecUserGroupID = " & selectedGroup(0) & ")"

        'Call GblFunc_Populate_List(StrSQL, "Security_GroupPermissions", Form_FMA_Security.List_GroupPermissions)
        Dim listGroupPermissions As DataTable = CommonDataFunctions.GetSQLDatatable(StrSQL)
        DataBinding.BindListView(listGroupPermissions, Me.List_GroupPermissions)

    End Sub
    Private Sub FillListMembers()
        Dim StrSQL As String
        Dim selectedGroup As DataRow = Me.List_Groups.SelectedItem
        StrSQL = "SELECT SecUserMember_ID, L_Consultant.Con_Name as 'Name'"
        StrSQL = StrSQL & " FROM Sec_UserMembers INNER JOIN L_Consultant ON Sec_UserMembers.SecUserMember_ConsultantID = L_Consultant.Con_ID"
        StrSQL = StrSQL & " WHERE (Sec_UserMembers.SecUserMember_UserGroupID = " & selectedGroup(0) & ")"

        'Call GblFunc_Populate_List(StrSQL, "Security_GroupMembersList", Form_FMA_Security.List_GroupMembers)
        Dim listMembers As DataTable = CommonDataFunctions.GetSQLDatatable(StrSQL)
        Me.List_GroupMembers.ItemsSource = listMembers
        Me.List_GroupMembers.Columns(0).IsVisible = False
        Me.List_GroupMembers.Columns(1).Width = New GridLength(140)
    End Sub

    Private Sub Btn_NewUserGroup_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_NewUserGroup.Click
        Try
           
            Dim StrSQL As String, Rst As DataTable, StrGroup As String

            StrGroup = InputBox("Please enter the name of the new group", "New User Group", StrGroup)

            If StrGroup = String.Empty Then
                Call CommonFuncs.DisplayMessage("Action cancelled", CommonDialog.CustomDialogIcons.Information, "No name given")
                Exit Sub
            End If

            StrSQL = "Select SecGroup_ID from Sec_UserGroups where SecGroup_Name = '" & StrGroup.Trim & "'"
            Rst = CommonDataFunctions.GetSQLDatatable(StrSQL)
            If Rst.Rows.Count > 0 Then
                Rst.Dispose()
                Call CommonFuncs.DisplayMessage("That group name is already in use, please use another", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            Else
                Rst.Dispose()
            End If

            StrSQL = "Insert into Sec_UserGroups (SecGroup_Name) VALUES('" & StrGroup.Trim & "')"
            If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then Exit Sub

            Me.FillListGroups()
            Me.FillAddUserToGroupsCombo()

            Call (New TasksEvents).GblFunc_Add_SysEvent("Security", "New user security group created, " & StrGroup)

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminSecurity - Btn_NewUserGroup_Click")
        End Try
    End Sub

    Private Sub Btn_RemoveConFromGroup_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_RemoveConFromGroup.Click
        Try
            Dim StrSQL As String
            Dim selectedGroupMember As DataRow = Me.List_GroupMembers.SelectedItem
            If selectedGroupMember Is Nothing Then
                Call CommonFuncs.DisplayMessage("Select member to remove", CommonDialog.CustomDialogIcons.Information, "Try Again")
                Exit Sub
            End If

            StrSQL = "Delete from Sec_UserMembers Where SecUserMember_ID = " & selectedGroupMember(0)
            If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then Exit Sub

            Me.FillListMembers()
            Me.FillListGroupPermissions()
            Dim listGroups As DataRow = Me.List_Groups.SelectedItem
            Call (New TasksEvents).GblFunc_Add_SysEvent("Security", selectedGroupMember(1) & " removed from security group " & listGroups(1))

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminSecurity - Btn_RemoveConFromGroup_Click")
        End Try
    End Sub

    Private Sub Btn_AddConToGroup_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_AddConToGroup.Click
        Try

            Dim StrSQL As String
            Dim selectedGroup As DataRow = Me.List_Groups.SelectedItem
            If selectedGroup Is Nothing Then
                Call CommonFuncs.DisplayMessage("Select Group first", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            ElseIf Me.Combo_GroupAddUser.SelectedIndex = -1 Then
                Call CommonFuncs.DisplayMessage("Select consultant first", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If
            'Dim strin As String = Me.Combo_GroupAddUser.SelectedValue.ToString
            StrSQL = "select * from Sec_UserMembers where SecUserMember_ConsultantID=" & Me.Combo_GroupAddUser.SelectedValue & " and SecUserMember_UserGroupID=" & selectedGroup(0)
            Dim result As DataTable = CommonDataFunctions.GetSQLDatatable(StrSQL)
            If result.Rows.Count > 0 Then
                CommonFuncs.DisplayMessage("User belong to the group already.", CommonDialog.CustomDialogIcons.Information, "Alert")
                Exit Sub
            End If
            StrSQL = "Insert into Sec_UserMembers"
            StrSQL = StrSQL & " (SecUserMember_ConsultantID, SecUserMember_UserGroupID, SecUserMember_EnteredBy)"
            StrSQL = StrSQL & " VALUES (" & Me.Combo_GroupAddUser.SelectedValue & ", " & selectedGroup(0) & ", '" & GlobalCRM.CurrentConName & "')"

            If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then Exit Sub

            Me.FillListMembers()
            Me.FillGroupMemberShip()

            Call (New TasksEvents).GblFunc_Add_SysEvent("Security", Me.Combo_GroupAddUser.Text & " added to security group " & selectedGroup(1))

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminSecurity - Btn_AddConToGroup_Click")
        End Try
    End Sub

    Private Sub Btn_RemoveGroupPermission_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_RemoveGroupPermission.Click
        Try

            Dim StrSQL As String
            Dim selectedGroupPermission As DataRowView = Me.List_GroupPermissions.SelectedItem
            If selectedGroupPermission Is Nothing Then
                Call CommonFuncs.DisplayMessage("Please select permission to remove", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If

            StrSQL = "Delete from Sec_Links where SecLink_ID = " & selectedGroupPermission(0)
            If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then Exit Sub

            Me.FillListGroupPermissions()
            Dim selectedGroup As DataRow = Me.List_Groups.SelectedItem
            If Not selectedGroup Is Nothing Then
                Call (New TasksEvents).GblFunc_Add_SysEvent("Security", "Security permission " & selectedGroupPermission(1) & " removed from security group " & selectedGroup(1))
            End If

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminSecurity - Btn_RemoveGroupPermission_Click")
        End Try
    End Sub

    Private Sub Btn_AddGroupPermission_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_AddGroupPermission.Click
        Try
            
            Dim StrSQL As String, StrDT As String, StrMess As String
            Dim selectedGroup As DataRow = Me.List_Groups.SelectedItem
            If selectedGroup Is Nothing Then
                Call CommonFuncs.DisplayMessage("Select Group first", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            ElseIf Me.Combo_AddGroupPermission.SelectedIndex = -1 Then
                Call CommonFuncs.DisplayMessage("Select values first", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If

            If Not Me.Txt_GroupExp.Text.Trim = String.Empty Then
                'If Not IsDate(Me.Txt_ExpiryDate) Then
                '    Call CommonFuncs.DisplayMessage("Please select a date", CommonDialog.CustomDialogIcons.Information, "Caution")
                '    Exit Sub
                'End If

                StrDT = "'" & Me.Txt_GroupExp.Text.Trim & "'"
                StrMess = ": Expires " & Me.Txt_GroupExp.Text
            Else

                StrDT = "Null"
                StrMess = ""
            End If

            StrSQL = "Insert into Sec_Links"
            StrSQL = StrSQL & " (SecLink_SecAccessID, SecLink_SecUserGroupID, SecLink_DTExp, SecLink_EnteredBy)"
            StrSQL = StrSQL & " Values(" & Me.Combo_AddGroupPermission.SelectedValue & ", " & selectedGroup(0) & ", " & StrDT & ", '" & GlobalCRM.CurrentConName & "')"

            If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then Exit Sub

            Me.FillListGroupPermissions()

            Call (New TasksEvents).GblFunc_Add_SysEvent("Security", "Security group " & selectedGroup(1) & " given permission " & Me.Combo_AddGroupPermission.Text & StrMess)

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminSecurity - Btn_AddGroupPermission_Click")
        End Try
    End Sub
End Class
